/*
  renderer.js - 渲染端控制逻辑
  - 渲染与更新 tab-strip
  - 绑定导航与地址栏事件
  - 同步顶部 UI 高度给主进程
  - 按当前 URL 控制“已完成登录认证”按钮显隐
*/
/* global electronAPI */

const tabsContainer = document.getElementById('tabs');
const newTabButton = document.getElementById('new-tab');
const backButton = document.getElementById('back');
const forwardButton = document.getElementById('forward');
const reloadButton = document.getElementById('reload');
const addressBar = document.getElementById('address-bar');
const checkUpdateBtn = document.getElementById('check-update');
const authBtn = document.querySelector('.auth-btn');
const tabStrip = document.getElementById('tab-strip');

// Windows 窗口控制 DOM
const winControls = document.getElementById('window-controls');
const winMinBtn = document.querySelector('.win-min');
const winMaxBtn = document.querySelector('.win-max');
const winCloseBtn = document.querySelector('.win-close');

// 仅在 Windows 显示自绘窗口控制
const isWindows = typeof navigator !== 'undefined' && /Windows/i.test(navigator.userAgent || '');
if (winControls) {
  winControls.style.display = isWindows ? 'flex' : 'none';
}
if (isWindows) {
  tabStrip.style.paddingLeft = '0px'
  winMinBtn && winMinBtn.addEventListener('click', () => electronAPI.minimizeWindow());
  winMaxBtn && winMaxBtn.addEventListener('click', () => electronAPI.toggleMaximizeWindow());
  winCloseBtn && winCloseBtn.addEventListener('click', () => electronAPI.closeWindow());
  if (electronAPI.onWindowState) {
    electronAPI.onWindowState((state) => {
      if (!winMaxBtn) return;
      winMaxBtn.textContent = state && state.isMaximized ? '❐' : '□';
    });
  }
  if (electronAPI.isWindowMaximized) {
    electronAPI.isWindowMaximized().then((m) => {
      if (winMaxBtn) winMaxBtn.textContent = m ? '❐' : '□';
    }).catch(() => {});
  }
}

let tabsState = [];

/**
 * 根据当前活动页面 URL 控制 .auth-btn 显隐
 * @param {string} activeUrl
 */
let protectedBaseUrl = null;

function setAuthButtonVisibility(activeUrl) {
  console.log(protectedBaseUrl, 'protectedBaseUrl');
  if (!authBtn) return;
  const shouldShow = !(typeof activeUrl === 'string' && activeUrl.startsWith(protectedBaseUrl));
  authBtn.style.display = shouldShow ? '' : 'none';
}


let cookiesValue = null
// 点击已完成登录按钮获取cookie
authBtn.addEventListener('click', () => {
  electronAPI.getCookies().then(async (cookies) => {
    console.log(cookies, 'cookies');
    if (cookies && cookies.length > 0) {
      cookiesValue = cookies;
      // 根据当前活动页的 URL 提取 origin，写入对应缓存
      const state = await electronAPI.getTabsState();
      const active = Array.isArray(state) ? state.find(t => t.isActive) : null;
      const url = active && active.url ? active.url : '';
      if (url) {
        await electronAPI.setCachedCookiesFor(url, cookies);
        // 关闭当前页签，并关闭授权窗口
        electronAPI.closeTab(active.id).then(() => {
          electronAPI.closeAuthWindow();
        });
      } else {
        // 回退：仍写入“当前活动”默认缓存
        await electronAPI.setCachedCookies(cookies);
        // 关闭当前页签，并关闭授权窗口
        electronAPI.closeTab(active.id).then(() => {
          electronAPI.closeAuthWindow();
        });
      }
    } else {
      alert('获取授权失败');
    }
  }).catch(() => {
    if (cookiesValue.length) {
      alert('获取授权成功');
    } else {
      alert('获取授权失败');
    }
  })
})

/**
 * 渲染 tab-strip：根据主进程广播的 tabs 状态构建标签 UI
 * @param {Array} state
 */
function renderTabs(state) {
  tabsContainer.innerHTML = '';

  state.forEach(tab => {
    const tabEl = document.createElement('div');
    tabEl.className = 'tab' + (tab.isActive ? ' active' : '');
    tabEl.dataset.tabId = String(tab.id);

    const favicon = document.createElement('img');
    favicon.className = 'favicon';
    favicon.src = tab.favicon || '';

    const title = document.createElement('span');
    title.className = 'title';
    title.textContent = tab.title || 'New Tab';

    const close = document.createElement('button');
    close.className = 'close';
    close.textContent = '×';
    close.title = 'Close';

    const isProtected = typeof tab.url === 'string' && tab.url.startsWith(protectedBaseUrl);

    if (isProtected) {
      close.style.visibility = 'hidden';
      close.style.pointerEvents = 'none';
      close.tabIndex = -1;
    } else {
      close.addEventListener('click', (e) => {
        e.stopPropagation();
        electronAPI.closeTab(tab.id);
      });
    }

    tabEl.appendChild(favicon);
    tabEl.appendChild(title);
    tabEl.appendChild(close);

    tabEl.addEventListener('click', () => {
      electronAPI.switchTab(tab.id);
    });

    tabsContainer.appendChild(tabEl);
  });

  const active = state.find(t => t.isActive);
  backButton.disabled = !(active && active.canGoBack);
  forwardButton.disabled = !(active && active.canGoForward);
  reloadButton.disabled = !active;
  if (active) {
    addressBar.value = active.url || '';
    setAuthButtonVisibility(active.url || '');
  } else {
    addressBar.value = '';
    setAuthButtonVisibility('');
  }
}

newTabButton.addEventListener('click', () => {
  // electronAPI.createTab();
});

backButton.addEventListener('click', () => electronAPI.goBack());
forwardButton.addEventListener('click', () => electronAPI.goForward());
reloadButton.addEventListener('click', () => electronAPI.reload());

addressBar.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') {
    const value = addressBar.value.trim();
    electronAPI.navigate(value);
  }
});

if (checkUpdateBtn) {
  checkUpdateBtn.addEventListener('click', async () => {
    try {
      const result = await electronAPI.checkForUpdates();
      if (result && result.available) {
        alert(`发现新版本: ${result.latest}，当前版本: ${result.current}`);
      } else {
        alert('当前已是最新版本');
      }
    } catch (err) {
      alert('检查更新失败');
    }
  });
}

/**
 * 量测顶部 UI 高度并通过 IPC 上报给主进程，用于 BrowserView 布局
 */
function measureAndSyncTopUiHeight() {
  const topUi = document.getElementById('top-ui');
  if (!topUi) return;
  const rect = topUi.getBoundingClientRect();
  const height = Math.ceil(rect.height);
  electronAPI.setTopUiHeight(height);
}

/**
 * 创建并显示错误提示框
 * @param {string} message 错误信息
 */
function showErrorNotification(message) {
  // 创建通知容器
  const notification = document.createElement('div');
  notification.className = 'error-notification';
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
    border-radius: 4px;
    padding: 12px 20px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    z-index: 9999;
    max-width: 400px;
    font-size: 14px;
  `;
  
  // 创建标题
  const title = document.createElement('div');
  title.style.cssText = 'font-weight: bold; margin-bottom: 8px;';
  title.textContent = '应用启动失败';
  
  // 创建消息内容
  const content = document.createElement('div');
  content.textContent = message || '应用启动失败，请检查应用配置';
  
  // 创建关闭按钮
  const closeBtn = document.createElement('button');
  closeBtn.style.cssText = `
    position: absolute;
    top: 8px;
    right: 8px;
    background: none;
    border: none;
    font-size: 16px;
    cursor: pointer;
    color: #721c24;
  `;
  closeBtn.textContent = '×';
  closeBtn.onclick = () => document.body.removeChild(notification);
  
  // 组装通知
  notification.appendChild(title);
  notification.appendChild(content);
  notification.appendChild(closeBtn);
  
  // 添加到页面
  document.body.appendChild(notification);
  
  // 5秒后自动消失
  setTimeout(() => {
    if (document.body.contains(notification)) {
      document.body.removeChild(notification);
    }
  }, 5000);
}

/**
 * 初始化事件与初始渲染：订阅 tabs 状态、首次获取状态、绑定窗口 resize
 */
function init() {
  electronAPI.onTabsState((state) => {
    tabsState = state;
    renderTabs(state);
    measureAndSyncTopUiHeight();
  });
  electronAPI.getTabsState().then((state) => {
    tabsState = state;
    renderTabs(state);
    measureAndSyncTopUiHeight();
  });
  window.addEventListener('resize', measureAndSyncTopUiHeight);

  // 动态获取受保护地址前缀
  if (electronAPI.getAppConfig) {
    electronAPI.getAppConfig().then((cfg) => {
      if (cfg && cfg.protectedBaseUrl) {
        protectedBaseUrl = String(cfg.protectedBaseUrl);
      }
    }).catch(() => {});
  }
  
}

init();